package com.dci.controller.project;

import com.alibaba.fastjson.JSONObject;
import com.dci.model.project.ProjectTaskManager;
import com.dci.result.JsonData;
import com.dci.result.PageResult;
import com.dci.result.ResultInfo;
import com.dci.service.project.OutboundInfoService;
import com.dci.service.project.PlanFeedbackInfoService;
import com.dci.service.project.PlanInfoService;
import com.dci.service.project.ProjectInfoService;
import com.dci.util.UUIDBuild;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * All rights Reserved, Designed By 姑苏区政府大数据中心
 *
 * @version V1.0
 * @Title: null.java
 * @Package com.dci.controller.project
 * @Description: 储备库管理
 * @author: 张星亮
 * @date: 2019/2/25
 * @Copyright: 2019 姑苏区政府大数据中心. All rights reserved.
 * 注意：本内容仅限于姑苏区政府大数据中心内部传阅，禁止外泄以及用于其他的商业目
 */
@Controller
@RequestMapping("/projectTask")
public class ProjectTaskController {

    @Resource
    private ProjectInfoService projectInfoService;

    @Resource
    private PlanInfoService planInfoService;

    @Resource
    private PlanFeedbackInfoService feedbackInfoService;

    @Resource
    private OutboundInfoService outboundInfoService;

    @Value("${upload.path}")
    private String path;
    @Value("${upload.url}")
    private String url;
    @Value("${upload.urlP}")
    private String urlP;


    /**
     * 任务发布
     *
     * @param
     * @return JsonData 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @PostMapping("/approvalAndSaveList")
    @ResponseBody
    public JsonData approvalAndSave(@RequestBody ProjectTaskManager projectTaskManager) {
       try{
           // JSONObject jsonObject = JSONObject.parseObject(formData);
           // String userId = (String) jsonObject.get("userId");
           projectTaskManager.setId(UUIDBuild.getUUID());
           projectTaskManager.setCreateTime(new Date());
           projectTaskManager.setType("1");
           projectTaskManager.setStatus("0");
           JsonData result = projectInfoService.saveProtectList(projectTaskManager);
           return result;
       }catch (Exception e) {
           e.printStackTrace();
           return   JsonData.success(null, 911);
       }
    }

    /**
     * 发布通知
     *
     * @param
     * @return ResultInfo 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping(value = "/SaveNotice", method = RequestMethod.POST)
    @ResponseBody
    public JsonData SaveNotice(@RequestParam("file") MultipartFile[] file,@RequestParam("form") String form) {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyymmddHHMMss");
        String address = df.format(now);
        String filePath = path + File.separator + address + "/";
        String fileNames = "";
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        if (file.length != 0) {
            for (MultipartFile files : file) {
                String fileName = files.getOriginalFilename();
                if (fileNames == "") {
                    fileNames += fileName;
                } else {
                    fileNames += ',' + fileName;
                }
                try {
                    files.transferTo(new File(fileDir.getAbsolutePath(), fileName));
                } catch (IOException e) {
                    continue;
                }
            }
        }

        /* 数据库存储的相对路径 */
        String urlPath = url + "/" + address + "/";
        JSONObject jsonObject = JSONObject.parseObject(form);
        ProjectTaskManager projectTaskManager = JSONObject.toJavaObject(jsonObject, ProjectTaskManager.class);
        projectTaskManager.setFileAddress(urlPath);
        projectTaskManager.setTaskAnnexName(fileNames);
        projectTaskManager.setType("0");
        return projectInfoService.SaveNotice(projectTaskManager);
    }


    /**
     * 根据条件查询项目列表,分页--任务发布
     *
     * @param projectTaskManager
     * @return PageResult 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping(value = "/getProjectNoticeList")
    @ResponseBody
    public PageResult selectProjectNoticeList(@RequestBody ProjectTaskManager projectTaskManager) {
        try {
            if(!StringUtils.isEmpty(projectTaskManager.getTaskName())){
                projectTaskManager.setTaskName(projectTaskManager.getTaskName().replaceAll("%","\\\\%")
                        .replaceAll("_","\\\\_"));
            }
            if(!StringUtils.isEmpty(projectTaskManager.getTaskObject())){
                projectTaskManager.setTaskObject(projectTaskManager.getTaskObject().replaceAll("%","\\\\%")
                        .replaceAll("_","\\\\_"));
            }
            PageResult result = projectInfoService.selectProjectNoticeList(projectTaskManager);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.fail(911);
        }
    }

    /**
     * 根据主键查询详细
     *
     * @param projectTaskManager
     * @return JsonData 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping(value = "/getProjectList")
    @ResponseBody
    public JsonData selectProjectByPrimaryKey(@RequestBody ProjectTaskManager projectTaskManager) {
        try {
            JsonData result = projectInfoService.selectProjectByPrimaryKey(projectTaskManager);
            return result;
        } catch (Exception e) {
            return JsonData.success(null, 911);
        }
    }


    /**
     * 修改阅读状态
     * @param id
     * @return
     */
    @RequestMapping("/updateReadStatus")
    @ResponseBody
    public ResultInfo updateReadStatus(@RequestParam("id") String id) {
        ResultInfo resultInfo = null;
        try{
            ProjectTaskManager record = new ProjectTaskManager();
            record.setId(id);
            resultInfo = projectInfoService.updateReadStatus(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultInfo;
    }


    /**
     * 读取后附件上传
     *
     * @param
     * @return ResultInfo 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping(value = "/UpdateNotice", method = RequestMethod.POST)
    @ResponseBody
    public JsonData UpdateNotice(@RequestParam("file") MultipartFile[] file,@RequestParam("form") String form) {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyymmddHHMMss");
        String address = df.format(now);
        String filePath = path + File.separator + address + "/";
        String fileUpdates = "";
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        if (file.length != 0) {
            for (MultipartFile files : file) {
                String fileName = files.getOriginalFilename();
                if (fileUpdates == "") {
                    fileUpdates += fileName;
                } else {
                    fileUpdates += ',' + fileName;
                }
                try {
                    files.transferTo(new File(fileDir.getAbsolutePath(), fileName));
                } catch (IOException e) {
                    continue;
                }
            }
        }

        /* 数据库存储的相对路径 */
        String urlPath = url + "/" + address + "/";
        JSONObject jsonObject = JSONObject.parseObject(form);
        ProjectTaskManager projectTaskManager = JSONObject.toJavaObject(jsonObject, ProjectTaskManager.class);
        projectTaskManager.setUpdateFileAddress(urlPath);
        projectTaskManager.setTaskAnnexUpdate(fileUpdates);
        return projectInfoService.UpdateNotice(projectTaskManager);
    }

}
